/* 审批流程事件 */
import jQuery from 'jquery';
import { validarelationProcessList } from "../../RuntimeForm/RelationProcess1/RelationProcess1";//校验关联流程
import getInitiateFormData from '../../framework/common/utils/getInitiateFormData';//获取流程表单数据
import request from "../../framework/common/utils/request";
import mymessage from "../../framework/common/utils/message";
import { globalModule } from '../../approval';
import { Modal, message} from 'antd';
import md5 from 'js-md5';
import { retryRequest, fileIsUploading } from '../../framework/common/utils';
import eventBus from '../../framework/common/eventBus';
import { initAllStepData } from "../../RuntimeForm/ApproveStep/stepUtility";/*审批步骤数据清洗*/

//同意审批入口
export function submitApproveForm({
    enable_sign_pwd,//是否存在签章校验 RollBack|Pass会有
    isValid,//Pass需要，且第一次由外面按钮触发时 = 'valid'
    manual_execution,//Pass RollBack会有
    steps,//审批路径
    tplData,
    params,
    urlPrefix,
    approveType="Pass",
    isReinitiate = false,//是否重新发起，重新发起需要给true
    setLoading//父组件更新确定按钮loading状态方法
}){
    switch(approveType){
        case "Initiate"://发起
            initiateApprove({
                steps: steps,//步骤路径
                tplData: tplData,
                params: params,
                urlPrefix: urlPrefix,
                approveType: approveType,
                setLoading: setLoading//确定按钮的状态方法
            });//发起流程
            break;
        case "Pass"://同意
        case "Vote"://表决
        case "Book"://归档
            Pass({
                isReinitiate: isReinitiate,
                isValid: isValid,
                enable_sign_pwd,
                manual_execution: manual_execution,
                steps: steps,//审批路径
                tplData: tplData,
                params: params,
                urlPrefix: urlPrefix,
                approveType: approveType,
                setLoading: setLoading,//父组件更新确定按钮loading状态方法
            });
            break;
        case "RollBack"://同意
            RollBack({
                enable_sign_pwd: enable_sign_pwd,
                manual_execution: manual_execution,
                tplData: tplData,
                params: params,
                approveType: approveType,
                setLoading: setLoading//父组件更新确定按钮loading状态方法
            });
            break;
        case "Consult"://发起协商
            Consult({
                enable_sign_pwd: enable_sign_pwd,
                manual_execution: manual_execution,
                tplData: tplData,
                params: params,
                approveType: approveType,
                setLoading: setLoading//父组件更新确定按钮loading状态方法
            });
            break;
        case "ReplyConsult"://发起协商
            ReplyConsult({
                enable_sign_pwd: enable_sign_pwd,
                manual_execution: manual_execution,
                tplData: tplData,
                params: params,
                approveType: approveType,
                setLoading: setLoading//父组件更新确定按钮loading状态方法
            });
            break;
        case "Assigned"://交办
            Assigned({
                enable_sign_pwd: enable_sign_pwd,
                manual_execution: manual_execution,
                tplData: tplData,
                params: params,
                approveType: approveType,
                setLoading: setLoading//父组件更新确定按钮loading状态方法
            });
            break;
        case "Terminate"://终止
            Terminate({
                enable_sign_pwd,
                manual_execution: manual_execution,
                steps: steps,//审批路径
                tplData: tplData,
                params: params,
                urlPrefix: urlPrefix,
                approveType: approveType,
                setLoading: setLoading,//父组件更新确定按钮loading状态方法
            });
            break;
        case "Cancel"://作废
            Cancel({
                enable_sign_pwd,
                manual_execution: manual_execution,
                tplData: tplData,
                params: params,
                urlPrefix: urlPrefix,
                approveType: approveType,
                setLoading: setLoading,//父组件更新确定按钮loading状态方法
            });
            break;
        case "AddSign"://加签
            AddSign({
                enable_sign_pwd,
                manual_execution: manual_execution,
                steps: steps,//审批路径
                tplData: tplData,
                params: params,
                urlPrefix: urlPrefix,
                approveType: approveType,
                setLoading: setLoading,//父组件更新确定按钮loading状态方法
            });
            break;
        default:
            console.log(approveType + "审批方法还未实现")
            break;
    }
}

//重置弹出框loading
function setLoadingState(){
    eventBus.publish("setAproveBtnLoading.update", false);//1.重置发起审批“确定”按钮loading
    eventBus.publish("setSignBtnLoading.update", false);//2.重置签章密码弹出框“确定”按钮loading
    eventBus.publish("setStepBtnLoading.update", false)//3.重置确认路径弹出框“确定”按钮loading
    eventBus.publish("setAddStepLoading.update", false)//4.重置添加步骤审批“确定”按钮loading
}

//发起流程入口，实际只是用来获得步骤路径，并弹出确认步骤路径框，实际的发起，在确认步骤路径框的“确定按钮”内调用
export function showInitiateSteps({
    params,
    tplData,
    approveType,
    setEditModelInfo,//设置确认步骤路径弹出框的方法
    beforeAjax,//发起确认步骤路径请求前的事件，用于设置发起前的loading状态
    success,//请求成功后事件，用于充值发起前的loading状态
    error//请求失败后事件，用于充值发起前的loading状态
}){
    let formData = getInitiateFormData({
        params: params, 
        tplData: tplData, 
        approveType: approveType,//审批类型
        type: 'getstep'
    });
    if(formData === false){//收集数据校验没成功
        return;
    }
    formData.manual_execution = false;//人工干预判断是否继续执行 todo 老代码写死为false，不知道为什么
    let keyParm = md5(JSON.stringify(formData));
    // setEditModelInfo({
    //     showStepEditModal: true//显示确认步骤弹出框
    // });//显示确认步骤路径弹框 临时注释，获取发起步骤路径，不要出现步骤路径遮罩

    beforeAjax?.();

    //获取确认步骤路径
    return request({
        url: "/flowinstance/process/get-initiate-steps",
        method: "POST",
        data:formData,
        headers: { 'vtk': keyParm },
        needCancelToken: true
    }).then(
        function (result) {
            if (result.code == 1) {
                //步骤路径数据清洗
                let stepInfo = initAllStepData({
                    opinion: "",
                    stepData: result.data,
                    multiUserSelect: tplData.ProcessInfo.MultiUserSelect//有这个参数，需要把多人步骤的用户默认全选 为什么不后端做这个逻辑？
                });//初始化审批步骤数据清洗
                
                //显示确认步骤路径弹框，实际发起审批，在步骤弹框内
                setEditModelInfo({
                    //步骤信息
                    actual_steps: stepInfo.actual_steps,//不包括branch步骤
                    approveSteps: stepInfo.approveSteps,//包括branch步骤，branch是选择分支步骤的信息
                    validateResult: stepInfo.validateResult,//步骤错误信息

                    showStepEditModal: true,//显示确认步骤弹出框
                });
            }else{
                success?.();
            }
        },
        function(result){
            error?.(result);
        }
    );
}

//发起审批
export function initiateApprove({
    steps,//审批路径
    tplData,
    params,
    urlPrefix,
    approveType="Initiate",
    setLoading//父组件更新确定按钮loading状态方法
}){
        var initiate_param = getInitiateFormData({
            tplData:tplData, 
            params:params,
            approveType: approveType
        });//审批所需的表单数据
        if(initiate_param === false){//如果收集数据失败，不做请求
            setLoading(true)
            return;
        }
        
        initiate_param.branch_choose = []; //选分支 历史代码写死为空数组
        initiate_param.actual_steps = steps;//审批路径

        let manual_execution = false;//老代码发起这里是写死的false
        initiate_param.manual_execution = manual_execution;

        var jsonParam = JSON.stringify(initiate_param);
        var keyParm = md5(jsonParam);
        setLoading(true)
        retryRequest({
            url: '/flowinstance/process/initiate?prc_name=' + initiate_param._prc_name_,
            method: "POST",
            data: initiate_param,
            headers: { 'vtk': keyParm },
            retryInterface: function(options) {
                //重置需要再次请求的参数
                setLoading(true)
                options.data.manual_execution = true;
                var keyParm = md5(JSON.stringify(options.data));
                options.headers.vtk= keyParm;
                return options;
            },
            success:function(result){
                setLoading(false)
                if(!result){//没有任何返回值，不做处理
                    return;
                }
                if (result.code == 1) {
                    globalModule.refreshParentWindow({ approveType:approveType, tplData: tplData});//回刷erp列表
                    message.success('发起成功');
                    setLoading(true)
                    setTimeout(function() {
                        var href = "/flowinstance/approval/index?action=done&node_id=" + result.data.node_id + "&proc_id=" + result.data.proc_id + "&package_id=" + result.data.package_id + "&oid=";
                        if (result.data.parent_id) {
                            href = href + '&parent_id=' + result.data.parent_id;
                        }
                        if (urlPrefix) {
                            href = urlPrefix + href;
                        }
                        window.location.href = href;
                    }, 602);
                }
            },
            error:function(){
                setLoading(false)
                mymessage.info({
                    content: "发起流程失败",
                    afterClose:function(){
                        
                    }
                });
            }
        })
}

//Pass同意 Book归档
export function Pass({
    enable_sign_pwd = false,//是否开启了签章
    manual_execution = false,//是否需要二次确认
    isValid,//只有第一次点按钮，才传入这个值 = valid，就是不管开不开签章，都强行校验一次
    isReinitiate = false,//是否重新发起
    steps=[],//审批路径，审批中，初次发起为空，如果需要确认步骤路径，由确认步骤路径提供
    tplData,
    params,
    urlPrefix,
    approveType="Pass",
    setLoading//父组件更新确定按钮loading状态方法
}){
        var initiate_param = getInitiateFormData({
            tplData:tplData, 
            params:params,
            approveType:approveType
        });//审批所需的表单数据
        if(initiate_param === false){//如果收集数据失败，不做请求
            setLoadingState();//重置按钮loading状态
            return;
        }

        var opt_type = approveType;


        initiate_param.actuals = steps.slice(1);
        initiate_param.activeStep = steps[0];
        initiate_param.branch_choose = []; //选分支 历史代码写死为空数组

        var url = '/flowinstance/approval/pass';
        if (isValid == 'valid') {
            url = '/flowinstance/approval/valid-pass'
        }
        url = url + "?prc_name=" + initiate_param._prc_name_;
        
        initiate_param.manual_execution = manual_execution;

        if(isReinitiate){//重新发起
            initiate_param.table_val_md5 = '';
        }
        let jsonParam = JSON.stringify(initiate_param);
        let keyParm = md5(jsonParam);

        setLoading(true);
        eventBus.publish("setAddStepLoading.update", true)//添加步骤审批“确定”按钮loading
        retryRequest({
            needCancelToken: true,//允许取消请求
            url: url,
            method: "POST",
            data: initiate_param,
            headers: { 'vtk': keyParm },
            retryInterface: function(options) {
                //重置需要再次请求的参数
                eventBus.publish("setAddStepLoading.update", true)//添加步骤审批“确定”按钮loading
                setLoading(true);
                options.data.manual_execution = true;
                var keyParm = md5(JSON.stringify(options.data));
                options.headers.vtk= keyParm;
                return options;
            },
            success:function(result){
                if(isValid != 'valid' && result.data && result.data.table_val_md5){
                    params.table_val_md5 = result.data.table_val_md5;
                }
                if (result.code == 1) {
                    if (isValid == 'valid') {//1.首次一定会满足这个条件
                        if(enable_sign_pwd){//1.1 开启了签章
                            eventBus.publish("showSignModal.update", {
                                showSignModelModal: true//显示签章密码弹框
                            });//发起由签章组件触发
                        }else{//1.2 没开签章，则自动再发一次请求
                            //再次发起
                            Pass({
                                enable_sign_pwd: enable_sign_pwd,
                                manual_execution: manual_execution,
                                isValid:'',//第二次请求，不需要这个参数
                                isReinitiate: isReinitiate,
                                steps: steps,
                                tplData: tplData,
                                params: params,
                                urlPrefix: urlPrefix,
                                approveType: approveType,
                                setLoading: setLoading
                            });//把默认参数传一遍，再请求一次
                        }
                    } else {
                        globalModule.refreshParentWindow({ approveType:approveType, tplData: tplData});//回刷erp列表
                        setTimeout(function() {
                            globalModule.afterWorkflowApprove({
                                callBack: function () {
                                    window.location.href = window.location.href;
                                }
                            });//OA系统打开,操作完成之后,做OA的动作
                        }, 602);
                    }
                } else if (result.code == 2) {
                    if (isValid == 'valid') {
                        //再次发起
                        Pass({
                            enable_sign_pwd: enable_sign_pwd,
                            manual_execution: manual_execution,
                            isValid:'',//第二次请求，不需要这个参数
                            isReinitiate: isReinitiate,
                            steps: steps,
                            tplData: tplData,
                            params: params,
                            urlPrefix: urlPrefix,
                            approveType:approveType,
                            setLoading: setLoading
                        });//把默认参数传一遍，再请求一次
                        return;
                    }
                    if (result.data.actuals && result.data.actuals.length) {//如果存在步骤
                        eventBus.publish("showApproveStep.update", result.data);//显示确认路径弹出框，再次同意在弹出框内进行
                    } else {
                        globalModule.refreshParentWindow({ approveType:approveType, tplData: tplData});//回刷erp列表
                        setTimeout(function() {
                            globalModule.afterWorkflowApprove({
                                callBack: function () {
                                    window.location.href = window.location.href;
                                }
                            });//OA系统打开,操作完成之后,做OA的动作
                        }, 602);
                    }
                } else {
                    setLoadingState();//重置按钮loading状态
                }
            },
            error:function(error){
                setLoadingState();//重置按钮loading状态
                if(error.message === "canceled"){
                    //主动取消的请求，不做提示
                }else{
                    mymessage.info({
                        content: "流程审批失败",
                        afterClose:function(){
                            
                        }
                    });
                }
            }
        })
}

//驳回
export function RollBack({
    enable_sign_pwd = false,//是否需要签章密码
    manual_execution = false,//是否需要二次确认
    tplData,
    params,
    approveType="RollBack",
    setLoading//父组件更新确定按钮loading状态方法
}){
    var initiate_param = getInitiateFormData({
        tplData:tplData, 
        params:params,
        approveType:approveType
    });//审批所需的表单数据
    if(initiate_param === false){//如果收集数据失败，不做请求
        setLoadingState();//重置按钮loading状态
        return;
    }

    //发起组织，跟别的类型还不一样，单独放在station内
    initiate_param.station = {
        station_guid: initiate_param.initiater.initiater_org_id,
        station_name: initiate_param.initiater.initiater_org_name
    };
    //在上面赋值后，再删除原有的数据
    delete initiate_param.initiater.initiater_org_id;
    delete initiate_param.initiater.initiater_org_name;

    initiate_param.node_id = tplData.NodeInfo.node_id;

    // param.initiater = {
    //     initiater_id: tplData.CurUserGUID,
    //     initiater_name: tplData.CurUserName
    // };
    
    initiate_param.manual_execution = manual_execution;
    initiate_param.only_do_validate = !!enable_sign_pwd;

    var url = '/flowinstance/approval/reject';
    url = url + "?prc_name=" + initiate_param._prc_name_;

    console.log(approveType + '要提交的数据', initiate_param);
    setLoading(true);
    retryRequest({
        needCancelToken: true,//允许取消请求
        url: url,
        method: "POST",
        data: initiate_param,
        retryInterface: function(options) {
            //重置需要再次请求的参数
            setLoading(true);
            options.data.manual_execution = true;
            var keyParm = md5(JSON.stringify(options.data));
            options.headers.vtk= keyParm;
            return options;
        },
        success:function(resObj){
            if (resObj.code == 1) {
                if (enable_sign_pwd) {//开启了签章
                    eventBus.publish("showSignModal.update", {
                        showSignModelModal: true//显示签章密码弹框
                    });//发起由签章组件触发
                } else {
                    globalModule.refreshParentWindow({ approveType:approveType, tplData: tplData});//回刷erp列表
                    setTimeout(function() {
                        globalModule.afterWorkflowApprove({
                            callBack: function () {
                                window.location.href = window.location.href;
                            }
                        });//OA系统打开,操作完成之后,做OA的动作
                    }, 602);
                }
            } else {
                setLoadingState();//重置按钮loading状态
            }
        },
        error:function(error){
            setLoadingState();//重置按钮loading状态
            if(error.message === "canceled"){
                //主动取消的请求，不做提示
            }else{
                mymessage.info({
                    content: "流程驳回失败",
                    afterClose:function(){
                        
                    }
                });
            } 
        }
    })
}
//终止
export function Terminate({
    enable_sign_pwd = false,//是否需要签章密码
    manual_execution = false,//是否需要二次确认
    tplData,
    params,
    approveType="Terminate",
    setLoading//父组件更新确定按钮loading状态方法
}){
    var initiate_param = getInitiateFormData({
        tplData:tplData, 
        params:params,
        approveType:approveType
    });//审批所需的表单数据
    if(initiate_param === false){//如果收集数据失败，不做请求
        setLoadingState();//重置按钮loading状态
        return;
    }

    initiate_param.node_id = tplData.NodeInfo.node_id;
    initiate_param.manual_execution = manual_execution;
    initiate_param.only_do_validate = !!enable_sign_pwd;

    var url = '/flowinstance/approval/termination';
    url = url + "?prc_name=" + initiate_param._prc_name_;

    console.log(approveType + '要提交的数据', initiate_param);
    setLoading(true);
    retryRequest({
        needCancelToken: true,//允许取消请求
        url: url,
        method: "POST",
        data: initiate_param,
        retryInterface: function(options) {
            //重置需要再次请求的参数
            setLoading(true);
            options.data.manual_execution = true;
            var keyParm = md5(JSON.stringify(options.data));
            options.headers.vtk= keyParm;
            return options;
        },
        success:function(resObj){
            if (resObj.code == 1) {

                if (enable_sign_pwd) {//开启了签章
                    eventBus.publish("showSignModal.update", {
                        showSignModelModal: true//显示签章密码弹框
                    });//发起由签章组件触发
                }else{
                    globalModule.refreshParentWindow({ approveType:approveType});//回刷erp列表
                    setTimeout(function() {
                        globalModule.afterWorkflowApprove({
                            callBack: function () {
                                window.location.href = window.location.href;
                            }
                        });//OA系统打开,操作完成之后,做OA的动作
                    }, 602);
                }
            } else {
                setLoadingState();//重置按钮loading状态
            }
        },
        error:function(error){
            setLoadingState();//重置按钮loading状态
            if(error.message === "canceled"){
                //主动取消的请求，不做提示
            }else{
                mymessage.info({
                    content: "流程终止失败",
                    afterClose:function(){
                        
                    }
                });
            }
        }
    })
}

//作废
export function Cancel({
    enable_sign_pwd = false,//是否需要签章密码
    manual_execution = false,//是否需要二次确认
    tplData,
    params,
    approveType="Cancel",
    setLoading//父组件更新确定按钮loading状态方法
}){
    var initiate_param = getInitiateFormData({
        tplData:tplData, 
        params:params,
        approveType:approveType
    });//审批所需的表单数据
    if(initiate_param === false){//如果收集数据失败，不做请求
        setLoadingState();//重置按钮loading状态
        return;
    }

    initiate_param.manual_execution = manual_execution;
    initiate_param.only_do_validate = !!enable_sign_pwd;

    var url = '/flowinstance/approval/invalid';
    url = url + "?prc_name=" + initiate_param._prc_name_;

    console.log(approveType + '要提交的数据', initiate_param);
    setLoading(true);
    retryRequest({
        needCancelToken: true,//允许取消请求
        url: url,
        method: "POST",
        data: initiate_param,
        retryInterface: function(options) {
            //重置需要再次请求的参数
            setLoading(true);
            options.data.manual_execution = true;
            var keyParm = md5(JSON.stringify(options.data));
            options.headers.vtk= keyParm;
            return options;
        },
        success:function(resObj){
            if (resObj.code == 1) {

                if (enable_sign_pwd) {//开启了签章
                    eventBus.publish("showSignModal.update", {
                        showSignModelModal: true//显示签章密码弹框
                    });//发起由签章组件触发
                }else{
                    globalModule.refreshParentWindow({ approveType:approveType, tplData: tplData});//回刷erp列表
                    setTimeout(function() {
                        globalModule.afterWorkflowApprove({
                            callBack: function () {
                                window.location.href = window.location.href;
                            }
                        });//OA系统打开,操作完成之后,做OA的动作
                    }, 602);
                }
            } else {
                setLoadingState();//重置按钮loading状态
            }
        },
        error:function(error){
            setLoadingState();//重置按钮loading状态
            if(error.message === "canceled"){
                //主动取消的请求，不做提示
            }else{
                
            }
        }
    })
}

//加签
export function AddSign({
    enable_sign_pwd = false,//是否需要签章密码
    manual_execution = false,//是否需要二次确认
    tplData,
    params,
    approveType="AddSign",
    setLoading//父组件更新确定按钮loading状态方法
}){
    var initiate_param = getInitiateFormData({
        tplData:tplData, 
        params:params,
        approveType:approveType
    });//审批所需的表单数据
    if(initiate_param === false){//如果收集数据失败，不做请求
        setLoadingState();//重置按钮loading状态
        return;
    }

    initiate_param.node_id = tplData.NodeInfo.node_id;
    initiate_param.manual_execution = manual_execution;
    initiate_param.only_do_validate = !!enable_sign_pwd;
    var url = '/flowinstance/approval/add-sign';
    url = url + "?prc_name=" + initiate_param._prc_name_;

    console.log(approveType + '要提交的数据', initiate_param);
    setLoading(true);
    retryRequest({
        needCancelToken: true,//允许取消请求
        url: url,
        method: "POST",
        data: initiate_param,
        success:function(resObj){
            if (resObj.code == 1) {

                if (enable_sign_pwd) {//开启了签章
                    eventBus.publish("showSignModal.update", {
                        showSignModelModal: true//显示签章密码弹框
                    });//发起由签章组件触发
                }else{
                    globalModule.refreshParentWindow({ approveType:approveType, tplData: tplData});//回刷erp列表
                    setTimeout(function() {
                        globalModule.afterWorkflowApprove({
                            callBack: function () {
                                window.location.href = window.location.href;
                            }
                        });//OA系统打开,操作完成之后,做OA的动作
                    }, 602);
                }
            } else {
                setLoadingState();//重置按钮loading状态
            }
        },
        error:function(error){
            setLoadingState();//重置按钮loading状态
            if(error.message === "canceled"){
                //主动取消的请求，不做提示
            }else{
                mymessage.info({
                    content: "流程加签失败",
                    afterClose:function(){
                        
                    }
                });
            }
        }
    })
}

//交办
export function Assigned({
    tplData,
    params,
    approveType="Assigned",
    setLoading//父组件更新确定按钮loading状态方法
}){
    var initiate_param = getInitiateFormData({
        tplData:tplData, 
        params:params,
        approveType:approveType
    });//审批所需的表单数据
    if(initiate_param === false){//如果收集数据失败，不做请求
        setLoadingState();//重置按钮loading状态
        return;
    }
    var url = '/flowinstance/approval/assigned';
    url = url + "?prc_name=" + initiate_param._prc_name_;

    console.log(approveType + '要提交的数据', initiate_param);
    setLoading(true);
    retryRequest({
        needCancelToken: true,//允许取消请求
        url: url,
        method: "POST",
        data: initiate_param,
        success:function(resObj){
            if (resObj.code == 1) {
        
                globalModule.refreshParentWindow({ approveType:approveType, tplData: tplData});//回刷erp列表
                setTimeout(function() {
                    globalModule.afterWorkflowApprove({
                        callBack: function () {
                            window.location.href = window.location.href;
                        }
                    });//OA系统打开,操作完成之后,做OA的动作
                }, 602);
            } else {
                setLoadingState();//重置按钮loading状态
            }
        },
        error:function(error){
            setLoadingState();//重置按钮loading状态
          
        }
    })
}


//发起协商
export function Consult({
    tplData,
    params,
    approveType="Consult",
    setLoading//父组件更新确定按钮loading状态方法
}){
    var initiate_param = getInitiateFormData({
        tplData:tplData, 
        params:params,
        approveType:approveType
    });//审批所需的表单数据
    if(initiate_param === false){//如果收集数据失败，不做请求
        setLoadingState();//重置按钮loading状态
        return;
    }

    var url = '/flowinstance/approval/do-consult';
    url = url + "?prc_name=" + initiate_param._prc_name_;

    console.log(approveType + '要提交的数据', initiate_param);
    setLoading(true);
    retryRequest({
        needCancelToken: true,//允许取消请求
        url: url,
        method: "POST",
        data: initiate_param,
        success:function(resObj){
            if (resObj.code == 1) {
        
                globalModule.refreshParentWindow({ approveType:approveType, tplData: tplData});//回刷erp列表
                setTimeout(function() {
                    globalModule.afterWorkflowApprove({
                        callBack: function () {
                            window.location.href = window.location.href;
                        }
                    });//OA系统打开,操作完成之后,做OA的动作
                }, 602);
            } else {
                setLoadingState();//重置按钮loading状态
            }
        },
        error:function(error){
            setLoadingState();//重置按钮loading状态
          
        }
    })
}

//回复协商
export function ReplyConsult({
    tplData,
    params,
    approveType="ReplyConsult",
    setLoading//父组件更新确定按钮loading状态方法
}){
    var initiate_param = getInitiateFormData({
        tplData:tplData, 
        params:params,
        approveType:approveType
    });//审批所需的表单数据
    if(initiate_param === false){//如果收集数据失败，不做请求
        setLoadingState();//重置按钮loading状态
        return;
    }

    var url = '/flowinstance/approval/reply-consult';
    url = url + "?prc_name=" + initiate_param._prc_name_;

    console.log(approveType + '要提交的数据', initiate_param);
    setLoading(true);
    retryRequest({
        needCancelToken: true,//允许取消请求
        url: url,
        method: "POST",
        data: initiate_param,
        success:function(resObj){
            if (resObj.code == 1) {
        
                globalModule.refreshParentWindow({ approveType:approveType, tplData: tplData});//回刷erp列表
                setTimeout(function() {
                    globalModule.afterWorkflowApprove({
                        callBack: function () {
                            window.location.href = window.location.href;
                        }
                    });//OA系统打开,操作完成之后,做OA的动作
                }, 602);
            } else {
                setLoadingState();//重置按钮loading状态
            }
        },
        error:function(error){
            setLoadingState();//重置按钮loading状态
          
        }
    })
}
//添加步骤审批
export function addStepApprove({
    tplData,
    params,
    urlPrefix,
    approveType,
    manual_execution = false
}){
    let initiate_param = getInitiateFormData({
        tplData: tplData, 
        params: params,
        approveType: approveType
    });//审批所需的表单数据
    if(initiate_param === false){//如果收集数据失败，不做请求
        setLoadingState();//重置按钮loading状态
        return;
    }
    
    initiate_param.manual_execution = manual_execution;
    initiate_param.activityId = tplData.NodeInfo.activity_guid;

    let keyParm = md5(JSON.stringify(initiate_param));
    eventBus.publish("setAddStepLoading.update", true)//添加步骤审批“确定”按钮loading
    eventBus.publish("setAproveBtnLoading.update", true)//添加步骤审批“确定”按钮loading
    retryRequest({
        needCancelToken: true,//允许取消请求
        headers: { 'vtk': keyParm },
        data: initiate_param,
        method: 'POST',
        url: '/flowinstance/process/get-approve-steps',
        retryInterface: function(options) {
            //重置需要再次请求的参数
            eventBus.publish("setAddStepLoading.update", true)//添加步骤审批“确定”按钮loading
            eventBus.publish("setAproveBtnLoading.update", true)//添加步骤审批“确定”按钮loading
            options.data.manual_execution = true;
            var keyParm = md5(JSON.stringify(options.data));
            options.headers.vtk= keyParm;
            return options;        },
        success: function(result) {
            if (result.code == 1) {
                params.flow_id = result?.data?.flow_id;
                if(!params.flow_id){
                    console.log("警告！ 添加步骤审批返回值 params.flow_id 缺失！")
                }
                eventBus.publish("showApproveStep.update", result.data);//显示确认路径弹出框，再次同意在弹出框内进行
            } else {
                setLoadingState();//重置按钮loading状态
            }
        },
        error: function(error) {
            setLoadingState();//重置按钮loading状态
            if(error.message === "canceled"){
                //主动取消的请求，不做提示
            }else{
                mymessage.info({
                    content: "获取流程审批路径失败",
                    afterClose:function(){
                        
                    }
                });
            }
        }
    });
}

//去掉协商|回复协商的小点点
export function setConsultRead({
    tplData
}){

    if (tplData.NodeInfo.consults_unread_ids && tplData.NodeInfo.consults_unread_ids.length) {
        request({
            method: "post",
            url: '/flowinstance/approval/set-consult-read',
            data: { 
                node_ids: tplData.NodeInfo.consults_unread_ids
            }
        }).then(
            function(resObj){
                if (resObj.code == 1) {

                    //1.清空未读记录
                    tplData.NodeInfo.consults_unread_ids = [];
                    tplData.NodeInfo.consults_unread = 0;

                    //2.同时更新 按钮列表组件 以及 协商列表组件 的未读状态
                    eventBus.publish("setConsultRead.update");

                }
            },
            function(){

            }
        )
    }
}

//审批前校验，校验流程表单和相关流程等信息
export function beforeApproeValidate({
    form,//页脚表单区
    metadataManager,
    tplData,
    approveType,
    validateSuccess
}){

    new Promise((resolve, reject) => {

        //验证是否有上传中的附件
        let fileUploadingRes = fileIsUploading({
            tipMessage: "文件正在上传，请稍后操作。"
        })
        if(fileUploadingRes){
            return false;//存在上传中的附件不做后续校验
        }

        //1.校验footer区表单
        form.validateFields().then(function(res){

            //2.校验表单
            if (tplData.form.form_mode == 0 || tplData.form.form_mode == null) {
                //流程中心表单
                let errorInfo = metadataManager.getError();

                if(typeof errorInfo === "function"){
                    mymessage.info({
                        content: errorInfo()
                    });
                }//校验信息如果是function，执行一次function

                if(!errorInfo){//如果校验通过
                    resolve(true);//表单校验成功
                }

            }else{
                //外挂表单
                var $cf = jQuery("#form-runtime");
                var showErr = function(errmsg) {
                    if (errmsg) {
                        mymessage.info({
                            content: errmsg
                        });
                    }
                };
                $cf.checkRequired(function() {
                    $cf.getFormData(function() {
                        resolve(true);//表单校验成功
                    }, showErr);
                }, showErr, approveType);
            }
            
        }).catch(function(res){
            //footer区校验不通过
        });
    }).then(
        function(){//表单校验通过
            return new Promise((resolve, reject) => {
                //2.1关联流程校验
                let otherError = validarelationProcessList({
                    tplData: tplData
                });
                if(otherError.code === 1){//除了表单字段外，其他地方还存在错误
                    mymessage.info({
                        content: otherError.message
                    });
                    return;
                }else{
                    validateSuccess?.();//校验成功后，执行校验成功方法
                }
            })
        }
    );
}